package com.newtouch.bxzs.enterprise.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.newtouch.bxzs.common.base.BaseErrorEnum;
import com.newtouch.bxzs.common.base.BaseException;
import com.newtouch.bxzs.common.base.model.EnterpriseCustomer;
import com.newtouch.bxzs.common.base.model.EnterpriseCustomerGroup;
import com.newtouch.bxzs.common.base.model.EnterpriseCustomerGroupMap;
import com.newtouch.bxzs.common.base.util.EntityToBeanUtils;
import com.newtouch.bxzs.common.base.util.UserDetailUtil;
import com.newtouch.bxzs.enterprise.mapper.EnterpriseCustomerGroupMapMapper;
import com.newtouch.bxzs.enterprise.mapper.EnterpriseCustomerGroupMapper;
import com.newtouch.bxzs.enterprise.mapper.EnterpriseCustomerMapper;
import com.newtouch.bxzs.enterprise.model.bo.EnterpriseCustomerBO;
import com.newtouch.bxzs.enterprise.model.bo.EnterpriseCustomerDetailBO;
import com.newtouch.bxzs.enterprise.model.bo.EnterpriseCustomerGroupBO;
import com.newtouch.bxzs.enterprise.model.vo.EnterpriseCustomerGroupVO;
import com.newtouch.bxzs.enterprise.model.vo.EnterpriseCustomerVO;
import com.newtouch.bxzs.enterprise.service.EnterpriseCustomerGroupService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * 企业客户分组serviceImpl
 *
 * <p>
 * <b>History:</b>
 * <table border="1">
 * <tr>
 * <th>Date</th>
 * <th>Operator</th>
 * <th>Memo</th>
 * </tr>
 * <tr>
 * <td>2021/2/4 11:04</td>
 * <td>dingqianbin</td>
 * <td>Create</td>
 * </tr>
 * </table>
 *
 * @author dingqianbin
 * @version 1.0.0
 * @since 1.0.0
 */
@Service
public class EnterpriseCustomerGroupServiceImpl implements EnterpriseCustomerGroupService {

    @Autowired
    private EnterpriseCustomerGroupMapper enterpriseCustomerGroupMapper;

    @Autowired
    private EnterpriseCustomerGroupMapMapper enterpriseCustomerGroupMapMapper;

    @Autowired
    private EnterpriseCustomerMapper enterpriseCustomerMapper;

    /**
     * 静态变量：系统日志
     */
    private static final Log logger = LogFactory.getLog(EnterpriseCustomerGroupServiceImpl.class);

    @Override
    public List<EnterpriseCustomerGroupBO> getGroupList() {
        /*获取当前用户的分组信息*/
        List<EnterpriseCustomerGroupBO> groupList = enterpriseCustomerGroupMapper.getGroupList(Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId());
        /*判断是否为空*/
        if (CollectionUtils.isEmpty(groupList)) {
            return null;
        }
        return groupList;
    }

    @Override
    public Integer modifyEnterpriseCustomerGroup(EnterpriseCustomerGroupVO enterpriseCustomerGroupVO) {
        /*判断传入的参数是否为空*/
        if (BeanUtil.isEmpty(enterpriseCustomerGroupVO)) {
            logger.error("增加/修改企业客户分组信息请求参数为空！");
            throw new BaseException(BaseErrorEnum.REQUEST_DATA_NULL);
        }
        /*校验必填项*/
        if (StringUtils.isEmpty(enterpriseCustomerGroupVO.getEnterpriseCustomerGroupName())) {
            logger.error("增加/修改企业客户分组信息必填项未填！");
            throw new BaseException(BaseErrorEnum.REQUIRED_ITEM_NULL);
        }
        /*判断企业客户分组名称是否存在*/
        if (!this.checkGroupName(enterpriseCustomerGroupVO.getEnterpriseCustomerGroupName())) {
            logger.error("增加/修改企业客户分组信息企业客户分组名称已存在！");
            throw new BaseException(BaseErrorEnum.DATA_EXISTS);
        }
        EnterpriseCustomerGroup enterpriseCustomerGroup = new EnterpriseCustomerGroup();
        BeanUtil.copyProperties(enterpriseCustomerGroupVO, enterpriseCustomerGroup);
        String userId = Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId();
        Date date = new Date();
        /*设置修改用户ID*/
        enterpriseCustomerGroup.setUpdateUserId(userId);
        /*设置修改时间*/
        enterpriseCustomerGroup.setUpdateTime(date);
        /*判断企业客户分组ID是否为空，为空就新增，不为空则修改*/
        if (StringUtils.isEmpty(enterpriseCustomerGroup.getEnterpriseCustomerGroupId())) {
            /*设置创建用户ID*/
            enterpriseCustomerGroup.setCreateUserId(userId);
            /*设置创建时间*/
            enterpriseCustomerGroup.setCreateTime(date);
            /*插入企业客户分组信息*/
            return enterpriseCustomerGroupMapper.insert(enterpriseCustomerGroup);
        } else {
            return enterpriseCustomerGroupMapper.updateById(enterpriseCustomerGroup);
        }

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer deleteEnterpriseCustomerGroup(EnterpriseCustomerGroupVO enterpriseCustomerGroupVO) {
        /*判断传入的参数是否为空*/
        if (BeanUtil.isEmpty(enterpriseCustomerGroupVO)) {
            logger.error("删除企业客户分组请求参数为空！");
            throw new BaseException(BaseErrorEnum.REQUEST_DATA_NULL);
        }
        /*判断传入的企业客户分组ID集合是否为空*/
        if(CollectionUtils.isEmpty(enterpriseCustomerGroupVO.getEnterpriseCustomerGroupIds())) {
            logger.error("删除企业客户分组未选择需要删除的企业客户分组！");
            throw new BaseException(BaseErrorEnum.REQUIRED_ITEM_NULL);
        }
        /*先删除企业客户分组信息*/
        if (enterpriseCustomerGroupMapper.deleteBatchIds(enterpriseCustomerGroupVO.getEnterpriseCustomerGroupIds()) == 1) {
            /*然后删除该企业客户分组下的所有企业客户*/
            return enterpriseCustomerGroupMapMapper.delete(new QueryWrapper<EnterpriseCustomerGroupMap>().in("ENTERPRISE_CUSTOMER_GROUP_ID",enterpriseCustomerGroupVO.getEnterpriseCustomerGroupIds()));
        }
        return null;
    }

    @Override
    public Integer insertGroupCustomer(EnterpriseCustomerGroupVO enterpriseCustomerGroupVO) {
        this.checkParam(enterpriseCustomerGroupVO);
        /*创建一个企业客户与分组对应关系集合*/
        List<EnterpriseCustomerGroupMap> enterpriseCustomerGroupMapList = new ArrayList<>();
        String userId = Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId();
        Date date = new Date();
        /*遍历企业客户ID集合，整理到企业客户与分组对应关系集合*/
        for (String enterpriseCustomerId : enterpriseCustomerGroupVO.getEnterpriseCustomerIds()) {
            EnterpriseCustomerGroupMap enterpriseCustomerGroupMap = new EnterpriseCustomerGroupMap();
            enterpriseCustomerGroupMap.setEnterpriseCustomerId(enterpriseCustomerId);
            enterpriseCustomerGroupMap.setEnterpriseCustomerGroupId(enterpriseCustomerGroupVO.getEnterpriseCustomerGroupId());
            enterpriseCustomerGroupMap.setCreateUserId(userId);
            enterpriseCustomerGroupMap.setCreateTime(date);
            enterpriseCustomerGroupMap.setUpdateUserId(userId);
            enterpriseCustomerGroupMap.setUpdateTime(date);
            enterpriseCustomerGroupMapList.add(enterpriseCustomerGroupMap);
        }
        /*批量插入企业客户与分组对应关系表*/
        return enterpriseCustomerGroupMapMapper.insertBatch(enterpriseCustomerGroupMapList);
    }

    @Override
    public Integer deleteGroupCustomer(EnterpriseCustomerGroupVO enterpriseCustomerGroupVO) {
        this.checkParam(enterpriseCustomerGroupVO);
        /*移除该企业客户分组中选中的企业客户*/
        return enterpriseCustomerGroupMapMapper.delete(new QueryWrapper<EnterpriseCustomerGroupMap>().in("ENTERPRISE_CUSTOMER_ID", enterpriseCustomerGroupVO.getEnterpriseCustomerIds()).eq("ENTERPRISE_CUSTOMER_GROUP_ID",enterpriseCustomerGroupVO.getEnterpriseCustomerGroupId()));
    }

    @Override
    public EnterpriseCustomerBO getEnableAddCustomerList(EnterpriseCustomerVO enterpriseCustomerVO) {
        /*判断传入的参数是否为空*/
        if (BeanUtil.isEmpty(enterpriseCustomerVO)) {
            logger.info("获取可添加的企业客户列表请求参数为空！");
            throw new BaseException(BaseErrorEnum.REQUEST_DATA_NULL);
        }
        /*判断传入的企业客户分组ID是否为空*/
        if (StringUtils.isEmpty(enterpriseCustomerVO.getEnterpriseCustomerGroupId())) {
            logger.info("获取可添加的企业客户列表企业客户分组ID不能为空！");
            throw new BaseException(BaseErrorEnum.REQUIRED_ITEM_NULL);
        }

        List<EnterpriseCustomer> enterpriseCustomers = enterpriseCustomerMapper.getEnableAddCustomerList(enterpriseCustomerVO.getEnterpriseCustomerGroupId(), Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserJobNumber(), enterpriseCustomerVO.getEnterpriseCustomerName());
        EnterpriseCustomerBO enterpriseCustomerBO = new EnterpriseCustomerBO();
        if (CollectionUtils.isEmpty(enterpriseCustomers)) {
            enterpriseCustomerBO.setList(Collections.emptyList());
            enterpriseCustomerBO.setCount(0);
            return enterpriseCustomerBO;
        }
        enterpriseCustomerBO.setList(EntityToBeanUtils.copyBean(enterpriseCustomers, EnterpriseCustomerDetailBO.class));
        enterpriseCustomerBO.setCount(enterpriseCustomers.size());
        return enterpriseCustomerBO;
    }

    /**
     * 判断企业客户分组名称是否存在
     *
     * @param enterpriseCustomerGroupName 企业客户分组名称
     * @return boolean
     */
    private boolean checkGroupName(String enterpriseCustomerGroupName) {
        /*根据企业客户分组名称以及创建用户ID查询企业客户分组信息*/
        List<EnterpriseCustomerGroup> enterpriseCustomerGroups = enterpriseCustomerGroupMapper.selectList(new QueryWrapper<EnterpriseCustomerGroup>().eq("ENTERPRISE_CUSTOMER_GROUP_NAME", enterpriseCustomerGroupName).eq("CREATE_USER_ID",Objects.requireNonNull(UserDetailUtil.getUserDetail()).getUserId()));
        return CollectionUtils.isEmpty(enterpriseCustomerGroups);
    }

    /**
     * 校验传入的参数
     *
     * @param enterpriseCustomerGroupVO 企业客户分组VO
     */
    private void checkParam(EnterpriseCustomerGroupVO enterpriseCustomerGroupVO) {
        /*判断传入的参数是否为空*/
        if (BeanUtil.isEmpty(enterpriseCustomerGroupVO)) {
            logger.error("请求参数为空！");
            throw new BaseException(BaseErrorEnum.REQUEST_DATA_NULL);
        }
        /*判断传入的企业分组ID是否为空*/
        if (StringUtils.isEmpty(enterpriseCustomerGroupVO.getEnterpriseCustomerGroupId())) {
            logger.error("企业分组ID不能为空！");
            throw new BaseException(BaseErrorEnum.REQUIRED_ITEM_NULL);
        }
        /*判断传入的企业客户ID集合是否为空*/
        if (CollectionUtils.isEmpty(enterpriseCustomerGroupVO.getEnterpriseCustomerIds())) {
            logger.error("未选择需要添加到企业分组的企业客户！");
            throw new BaseException(BaseErrorEnum.REQUIRED_ITEM_NULL);
        }
    }
}
